package hephaestus.server.proxy;

import hephaestus.common.*;

import java.io.IOException;
import java.util.*;

public class ConnectionManager {
	private AuthenticationServer authServer;
	private Map<Long, ClientConnection> clients;
	private List<GameServer> gameServers;
	
	public ConnectionManager()
	{
		// TODO: Do these need to be Synchronized data structures?
		//       Does this class need Synchronized keywords everywhere? - OM
		clients = new HashMap<Long, ClientConnection>();
		gameServers = new ArrayList<GameServer>();
		authServer = null;
	}
	
	public boolean hasAuthenticationServer()
	{
		return (authServer != null);
	}
	
	public void registerAuthenticationServer(Connection connection)
	{
		if(!hasAuthenticationServer())
		{
			authServer = new AuthenticationServer(connection);
		}
	}
	
	public boolean hasGameServerCalled(String name)
	{
		for(GameServer gs : gameServers)
		{
			if(gs.isCalled(name))
			{
				return true;
			}
		}
		return false;
	}
	
	public void registerGameServer(Connection connection, String name)
	{
		if(!hasGameServerCalled(name))
		{
			gameServers.add(new GameServer(connection, name));
		}
	}
	
	public boolean authenticate(String username, String passhash)
	{
		if(hasAuthenticationServer())
		{
			// TODO: Authenticate login details
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public boolean isAlreadyConnected(String username)
	{
		for(ClientConnection client : clients.values())
		{
			if(client.isUser(username))
			{
				return true;
			}
		}
		return false;
	}
	
	public long clientConnected(String username, Connection connection)
	{
		long clientAuthID = ClientConnection.INVALID_AUTH_ID;
		if(!isAlreadyConnected(username))
		{
			ClientConnection client = new ClientConnection(username, connection);
			clients.put(client.getAuthID(), client);
			clientAuthID = client.getAuthID();
			System.out.println("# Client '" + username + "' connected [" + client.getIP() + "]");
		}
		return clientAuthID;
	}
	
	public void think() throws IOException
	{
		for(ClientConnection client : clients.values())
		{
			client.think();
		}
	}
}
